<template>
	<view class="topup">
		<g-navbar title="直营充值" />
		<view class="main">
			<view class="title">
				请选择充值金额：
			</view>
			<view class="select-amount-container">
				<view class="amount-item" @click="()=>{currentAmount= index;otherAmount = ''}"
					:class="index == currentAmount?'current':''" v-for="item,index in amountList" :key="index">
					{{item}}元
				</view>
			</view>
			<view class="other-amount-input-container">
				<view class="label">
					其他金额
				</view>
				<view class="input-wrapper">
					<input type="number" class="amount-input" placeholder-class="placeholder"
						placeholder="请输入其他充值金额，最低1元,最大10000" @input="amountInput" v-model="otherAmount" />
				</view>
			</view>
			<view class="btn-wrapper">
				<g-button btn_text="立即充值" :width="574" :height="100" :borderRadius="24" :disabled="isDisabled"
					@click="topup" />
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { Ref, ref, computed } from "vue";
	import { inRange } from 'lodash';
	import REST_URL from "@/http/http.restUrl";
	import {useStore} from 'vuex';
	import {ROUTE_TYPE} from '@/enum/router';
	import { GET_STORE_USERINFO } from '@/store/gettersType';
	
	const store = useStore();

	const currentAmount : Ref<number> = ref(0);

	const amountList : number[] = [50, 100, 300, 500];

	const otherAmount : Ref<string> = ref('');

	const isDisabled = computed(() => {
		return !(currentAmount.value >= 0 || inRange(otherAmount.value, 1, 10000))
	})


	let timer : number
	const amountInput = (e) => {
		currentAmount.value = -1;
		clearTimeout(timer)
		timer = setTimeout(() => {
			console.log(!!otherAmount.value.length)
			if (inRange(otherAmount.value, 1, 10000)) {
			} else if (otherAmount.value.length) {
				if (Number(otherAmount.value) > 10000) {
					otherAmount.value = '10000';
				} else {
					otherAmount.value = '1';
				}

			} else {
				otherAmount.value = '';
			}
		}, 500)
	}

	const topup = async () : Promise<void> => {
		await uni.loginManger.$interceptor;
		const options = {
			customer_id: store.getters[GET_STORE_USERINFO].id,
			recharge_amount: currentAmount.value >= 0 ? amountList[currentAmount.value] : otherAmount.value
		}
		await uni.http.POST(REST_URL.topupBalance, options);
		uni.prompt.$showToast('申请充值余额成功，待审核',3000);
		uni.navigateBack({
			success: () => {
				uni.$emit('updateHistoryList')
			}
		})
		// uni.router.route({
		// 	url:'/pages_topup/topup_entry/topupEntry',
		// 	type:ROUTE_TYPE.REDIRECTTO,
		// 	success:()=>{
		// 		uni.prompt.$showToast('申请充值余额成功，待审核',3000);
		// 		uni.$emit('updateHistoryList')
		// 	}
		// })
	}
</script>

<style scoped lang="scss">
	@import "./topup.scss";
</style>